package models

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/jinzhu/gorm"
	"wjp/syserror"
)

type PraiseLog struct {
	Model
	UserId 	int
	Key string
	Table 	string
	Flag 	bool
}

type TempPraise struct {
	Praise int
}

func UpdatePraise(table,key string,userid int) (pcnt int,err error){
	//事务
	d:=db.Begin()
	defer func() {
		if err !=nil{
			d.Rollback()
		}else{
			d.Commit()
		}
	}()

	var p PraiseLog
	err=d.Debug().Where("`key` = ? and `table` = ? and user_id = ?",key,table,userid).Take(&p).Error
	if err ==gorm.ErrRecordNotFound{
		fmt.Println("没有记录")
		p=PraiseLog{
			UserId:userid,
			Key:key,
			Table:table,
			Flag:false,
		}
	}else if err!=nil{
		return 0,err
	}else{
		logs.Info(p)
		if p.Flag{
			return 0,syserror.HasPraiseError{}
		}
	}
	p.Flag=true
	//保存流水
	if err = d.Save(&p).Error;err !=nil{
		return 0,err
	}
	//更新文章留言点赞数
	var (
		ppp TempPraise
	)
	err = d.Table(table).Where("`key`=?",key).Select("praise").Scan(&ppp).Error
	if err!=nil{
		return 0,err
	}
	pnum :=ppp.Praise+1
	if err = d.Table(table).Where("`key`=?",key).Update("praise",pnum).Error;err !=nil{

	}
	return pnum,err
}
